//
//  ZXBaseViewController.m
//  MortgageHelper
//
//  Created by apple on 16/6/28.
//  Copyright © 2016年 zhangxiang. All rights reserved.
//

#import "ZXBaseViewController.h"
#import "UINavigationController+FDFullscreenPopGesture.h"
#import "MGTipsViewController.h"


@interface ZXBaseViewController ()

@end

@implementation ZXBaseViewController

#pragma mark - 初始化设置
- (instancetype)init
{
    self = [super init];
    if (self) {
        // Custom initialization
        
    }
    return self;
}


-(instancetype)initWithSelfClassNib
{
    return [self initWithNibName:NSStringFromClass([self class]) bundle:nil];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        
    }
    return self;
}

#pragma mark - 控制器生命周期
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor add_colorWithRGBHexString:@"F1F1F1"];
    self.tabBarController.tabBar.translucent = NO;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.extendedLayoutIncludesOpaqueBars = NO;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationItem.leftBarButtonItem = [self leftBarButtonItem:nil];
    
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:YES];
    
//    [TalkingData trackPageBegin:NSStringFromClass(self.class)];
    

}
- (void)viewWillDisappear:(BOOL)animated
{
    
    [super viewWillDisappear:animated];
    if(!_hideDefaultBackButton) return;
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    
//    [TalkingData trackPageEnd:NSStringFromClass(self.class)];
    
    if (self.removeFromNavigationStackWhenDisappered)
    {// 判断是否要将当前控制器从导航控制器栈中移除，若是，则移除
        [self removeFromNavigationControllerStack];
    }
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{
//    @"%@释放了",NSStringFromClass([self class])
}

#pragma mark - UI

#pragma mark 提供导航栏右侧按钮 （纯图片）
- (UIBarButtonItem *)rightBarButtonWithName:(NSString *)name
                                  imageName:(NSString *)imageName
                                     target:(id)target
                                     action:(SEL)action
{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    if (imageName && ![imageName isEqualToString:@""]) {
        UIImage *image = [UIImage imageNamed:imageName];
        [btn setImage:image forState:UIControlStateNormal];
        
        UIImage *imageSelected = [UIImage imageNamed:[NSString stringWithFormat:@"%@_s",imageName]];
        if (imageSelected) {
            [btn setImage:imageSelected forState:UIControlStateSelected];
        }
        btn.frame = CGRectMake(0, 0, image.size.width, image.size.height);
    } else {
        btn.frame=CGRectMake(0, 0, 50, 30);
    }
    
    if (name && ![name isEqualToString:@""])
    {
        [btn setTitle:name forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont boldSystemFontOfSize:16];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.3] forState:UIControlStateHighlighted];
        [btn setTitleColor:[UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.3] forState:UIControlStateDisabled];
    }
    btn.titleEdgeInsets = UIEdgeInsetsMake(0, 13, 0, 0);
    
    [btn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:btn];
    return item;
}


#pragma mark 提供导航栏右侧按钮 （图片 + 文字）
- (UIBarButtonItem *)rightBarButtonWithName:(NSString *)name
                                  imageName:(NSString *)imageName
                                  textColor:(UIColor *)textColor
                                     target:(id)target
                                     action:(SEL)action{
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    
    if (imageName && ![imageName isEqualToString:@""]) {
        UIImage *image = [UIImage imageNamed:imageName];
        [btn setImage:image forState:UIControlStateNormal];
        
        UIImage *imageSelected = [UIImage imageNamed:[NSString stringWithFormat:@"%@_s",imageName]];
        if (imageSelected) {
            [btn setImage:imageSelected forState:UIControlStateSelected];
        }
        btn.frame = CGRectMake(0, 0, image.size.width, image.size.height);
    } else {
        btn.frame=CGRectMake(0, 0, 80, 30);
    }
    
    if (name && ![name isEqualToString:@""])
    {
        [btn setTitle:name forState:UIControlStateNormal];
        btn.titleLabel.font = [UIFont boldSystemFontOfSize:16];
        
        if (textColor) {
            [btn setTitleColor:textColor forState:UIControlStateNormal];
            [btn setTitleColor:textColor forState:UIControlStateHighlighted];
            [btn setTitleColor:textColor forState:UIControlStateDisabled];
        }else{
            [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.3] forState:UIControlStateHighlighted];
            [btn setTitleColor:[UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.3] forState:UIControlStateDisabled];
        }
        
    }
    btn.titleEdgeInsets = UIEdgeInsetsMake(0, 13, 0, 0);
    
    [btn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:btn];
    return item;
    
}


#pragma mark  提供导航栏左侧按钮默认样式
- (UIBarButtonItem *)leftBarButtonItem:(UIView *)leftButton
{
    
    if (self.navigationController.viewControllers.firstObject == self && !leftButton) {
        return nil;
    }
    if (!leftButton) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setImage:[UIImage imageNamed:@"fanhui"] forState:UIControlStateNormal];
        button.frame = CGRectMake(0, 0, 50, 44);
        [button addTarget:self action:@selector(goBackClick) forControlEvents:UIControlEventTouchUpInside];
        button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
        [button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        button.titleLabel.font = [UIFont systemFontOfSize:16];
        [button setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 0)];
        [button setTitle:@"" forState:UIControlStateNormal];
        return [[UIBarButtonItem alloc]initWithCustomView:button];

    }else{
        return [[UIBarButtonItem alloc]initWithCustomView:leftButton];
    }
}

#pragma mark - 触发事件

#pragma mark 设置是否掩藏导航栏默认返回按钮
- (void)setHideDefaultBackButton:(BOOL)hideDefaultBackButton
{
    _hideDefaultBackButton = hideDefaultBackButton;
    if (hideDefaultBackButton)
    {
        self.navigationItem.leftBarButtonItem = nil;
        self.navigationItem.hidesBackButton = YES;
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
        self.navigationController.fd_fullscreenPopGestureRecognizer.enabled = NO;
    }
    
}

#pragma mark  导航条左侧按钮点击事件
- (void)goBackClick
{
    [self.view endEditing:YES];
    NSLog(@"ctr3  %lu",self.navigationController.viewControllers.count);
    if (self.presentingViewController &&
        (!self.navigationController ||self == self.navigationController.viewControllers.firstObject)) {
        [self dismissViewControllerAnimated:YES completion:nil];
        
    }
    else{
        [self.navigationController popViewControllerAnimated:YES];
    }

}

#pragma mark - 功能接口

#pragma mark 检查是否登录
- (BOOL)checkIsLogin {
    //    if (!kUserInfoManage.isLogin) {
    //        YDLoginViewController *loginViewController = [[YDLoginViewController alloc] init];
    //        [self presentViewController:loginViewController animated:YES completion:nil];
    //        return NO;
    //    } else {
    //        //配置请求头参数
    //        [YDRequestService configeWithBaseUrl:[YDRequestHelper baseURLString] userInfo:(YDUserInfoModel <YDUserInfo> *)SharedUserModel];
    //    }
    return YES;
}


#pragma mark  将当前控制器从导航控制器栈中移除
- (void)removeFromNavigationControllerStack
{
    NSMutableArray *newArray = [self.navigationController.viewControllers mutableCopy];
    UIViewController *currentTypeViewController = nil;
    for (UIViewController *viewController in newArray) {
        if ([viewController isKindOfClass:[self class]])
        {
            currentTypeViewController = viewController;
        }
    }
    [newArray removeObject:currentTypeViewController];
    [self.navigationController setViewControllers:newArray animated:YES];
}

- (void)removeControllerFromIndex:(NSInteger )index{
    
    NSMutableArray *newArray = [self.navigationController.viewControllers mutableCopy];
    if (newArray.count>3) {
        UIViewController *currentTypeViewController = newArray[index];
        
        if (![currentTypeViewController isKindOfClass:[self class]]) {  // 非自己 就一处上一个
            [newArray removeObject:currentTypeViewController];
            [self.navigationController setViewControllers:newArray animated:YES];
        }
 
    }
}

#ifdef __IPHONE_9_0
- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}
#else
- (NSUInteger)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}
#endif

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void)showNetworkMessage:(NSString *)message error:(NSError *)error
{
    if (error.code==36003) {
        
        MGTipsViewController * Vc=[MGTipsViewController viewWithSelfNib];
        Vc.tipsViewType=MGTipsViewTypeNoNetWork;
        [Vc customerUI];
        Vc.tryAgain=^{
            [self tryAgianLoadData];
        };
        [self.view addSubview:Vc];
        [Vc mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view).with.insets(UIEdgeInsetsMake(0, 0, 0, 0));
        }];
        
    }else{
        [self showToastInViewController:message?message:error.userInfo[@"NSErrorMessageKey"]];
    }
   
}

// 子类重写这些方法
-(void)tryAgianLoadData{
    
}



@end
